<template>
  <div :id="uuid"></div>
</template>

<script setup lang="tsx">
import { computed, onMounted, onUnmounted, toRaw, useId, watch } from 'vue';
import { useEventSource } from '@boeyo/hooks';
import { useUserStore } from '@boeyo/portal';
import { realDataChart } from '@/utils/index';

const props = defineProps({
  measureInfo: {
    type: Object,
    default: () => ({}),
  },
});

const uuid = useId();

const options = {
  channelList: [
    {
      value: 'EIZ',
      label: 'EIZ-竖桥向',
      color: '#F16995',
    },
    {
      value: 'EIN',
      label: 'EIN-横桥向',
      color: '#77E3F9',
    },
    {
      value: 'EIE',
      label: 'EIE-纵桥向',
      color: '#DFC428',
    },
  ],
};
const legend = [
  {
    data: ['EIZ-竖桥向'],
    left: '10%',
    bottom: 0,
    orient: 'horizontal',
    icon: 'none', //不展示图标
    textStyle: {
      fontSize: 14,
      color: '#fff',
    },
  },
  {
    data: ['EIN-横桥向'],
    left: '45%',
    bottom: 0,
    orient: 'horizontal',
    icon: 'none', //不展示图标
    textStyle: {
      fontSize: 14,
      color: '#fff',
    },
  },
  {
    data: ['EIE-纵桥向'],
    left: '80%',
    bottom: 0,
    orient: 'horizontal',
    textStyle: {
      fontSize: 14,
      color: '#fff',
    },
    icon: 'none', //不展示图标
  },
];
const channels = computed(() => {
  return options.channelList.map((cur, index) => {
    const { color, value, label } = cur;
    return {
      color,
      label,
      name: value,
      grid: {
        show: true,
        top: '12%',
        left: `${33 * index}%`,
        bottom: 0,
        width: '32%',
        height: '80%',
        containLabel: true,
        borderWidth: 0,
      },
      // legend: {
      //   data: label,
      //   left: `${33 * index + 15}%`,
      //   bottom: 15,
      //   orient: 'horizontal',
      //   textStyle: {
      //     fontSize: 14,
      //     color: '#fff',
      //   },
      //   icon: 'none', //不展示图标
      // },
    };
  });
});

let renderChart;
let updateChartConfig;

const init = () => {
  console.log(channels.value, 'init');

  const { renderChart: _renderChart, updateChartConfig: _updateChartConfig } =
    realDataChart({
      title: false,
      target: document.getElementById(uuid),
      // direction: 'horizontal',
      channels: toRaw(channels.value),
      legend,
    });
  renderChart = _renderChart;
  updateChartConfig = _updateChartConfig;
  if (props.measureInfo.stationId) connect();
};

const info = computed(() => {
  return {
    code: props.measureInfo.stationId, //设备编码
    samplingRate: 100, //采样率
    latticeValue: 500, //格值
    intensity: 0, //烈度
    dataDelay: 0, //数据延迟
  };
});
const userStore = useUserStore();

const formatData = (cb) => {
  let data = {};
  const checkData = () => {
    let flag = false;
    if (Object.keys(data).length !== 3) return false;
    Object.values(data)
      .map((item) => item[0][0])
      .reduce((prev, cur) => {
        flag = prev === cur;
        return cur;
      });
    return flag;
  };
  const push = (_data) => {
    Object.keys(_data).forEach((_key) => {
      let key;
      switch (_key) {
        case 'Z':
          key = 'EIZ';
          break;
        case 'N':
          key = 'EIN';
          break;
        case 'E':
          key = 'EIE';
          break;
        default:
          break;
      }
      if (_key !== 'X') {
        data[key] = _data[_key];
      } else {
        info.value.intensity = _data[_key];
      }
    });
    if (checkData()) {
      cb(data);
      data = {};
    }
  };
  return push;
};

const push = formatData((data) => {
  const dataSource = {};
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      const element = data[key];
      dataSource[key] = element.reduce((prev, cur) => {
        if (cur[0] % 100 === 0) {
          const value = cur[1];
          cur[1] = value / info.value.latticeValue;
          prev.push(cur);
        }

        return prev;
      }, []);
    }
  }
  renderChart(dataSource, info.value.intensity.toFixed(2));
});

const random = Math.random().toString().slice(-6);
const { connect, disconnect } = useEventSource(
  computed(() => `/api/edge/sse/300/${random}/${info.value.code}`),
  {
    headers: {
      ['Authorization']: `Bearer ${userStore.token}`,
      'Content-Type': 'application/json',
      Accept: '*/*',
    },
    withCredentials: false,
    onMessage(res) {
      const data = JSON.parse(res);
      push(data);
    },
    onError(error) {
      console.log(error);
      disconnect();
    },
  },
);

onMounted(() => {
  init();
});

watch(
  () => props.measureInfo.stationId,
  () => {
    disconnect();
    connect();
    updateChartConfig(
      toRaw(channels.value).map((cur, index) => {
        return {
          ...cur,
          legend,
          grid: {
            show: true,
            top: '10%',
            left: `${33 * index}%`,
            width: '32%',
            height: '80%',
            containLabel: true,
            borderWidth: 0,
          },
        };
      }),
    );
  },
  { deep: true },
);

onUnmounted(disconnect);
</script>

<style lang="scss" scoped></style>
